# 导包
from datetime import tzinfo
from functools import wraps
from operator import mod
from os import write
from peewee import EXCEPTIONS, NoopModelSelect
from redis.client import Redis
import tornado.web

from bson.objectid import ObjectId

# 服务器
from tornado import httpserver
from werkzeug.datastructures import Headers

# 导入基础类
from base import BaseHandler

# 导入数据库操作类
from db import database, User, myser, MyMongo

mymongo = MyMongo()

import datetime

# python的时区库
import pytz

# 设置时区
tzinfo = pytz.timezone('Asia/Shanghai')

# 异步执行库
import peewee_async
import hashlib

import json, random

from tools import ret_json, send_mail, MyJwt, SendSms

import random
import redis

import re, asyncio
import requests

# 绘图库
from PIL import ImageDraw
from PIL import Image

# io库
import io

import time

# 导入工厂类
# from test_desgin import SimpleFactory

import os


# 文件上传接口
class Upload(BaseHandler):

    async def post(self):
        # 获取文件
        file = self.request.files['file']

        id = self.get_argument('id', None)

        filename = ''

        for i in file:
            # 设置文件名
            filename = i['filename']

            # 获取当前时间戳
            mytime = str(int(time.time()))

            # 获取前缀后缀
            last_file = os.path.splitext(filename)[-1]
            front_file = os.path.splitext(filename)[0]
            newfilename = front_file + '_' + mytime + last_file

            # 写文件
            with open('./static/' + newfilename, 'wb') as f:
                f.write(i['body'])
        if id:
            # 修改头像
            user = await self.application.objects.get(User, id=id)
            user.img = 'http://localhost:8888/static/%s' % newfilename

            # 异步
            await self.application.objects.update(user)

        return self.write(ret_json({'code': 200, 'meg': '文件上传成功', 'filename': newfilename}))


# 重定向到gitee  # 三方登录三步曲(1)
# 获取三方登录地址
class GetUrl(BaseHandler):

    async def get(self):
        gitee_url = SimpleFactory.get_url('gitee')
        dingding_url = SimpleFactory.get_url('dingding')
        weibo_url = SimpleFactory.get_url('weibo')

        return self.write({'dingding_url': dingding_url, 'gitee_url': gitee_url, 'weibo_url': weibo_url})


# 微博回调
class WeiBo_Back(BaseHandler):
    async def get(self):
        code = self.get_argument('code', None)

        res = SimpleFactory.get_info('weibo', '', '', code)

        username = res[0]
        img = res[1]

        user = await SimpleFactory.find_one(self.application.object, User, username)

        # 序列化
        user = [myser(i) for i in user]
        myjwt = MyJwt()
        if user:
            # 存在  返回用户信息
            username = user[0]['username']
            id = user[0]['id']
            token = myjwt.encode({'id': id})
            print(token)
            # return self.write(ret_json({'code':200,'username':username,'id':id}))
            self.redirect('http://localhost:8080/mystation/?id=%s&username=%s&token=%s' % (id, username, token))
        else:
            # 不存在 首次登录    入库
            user = await SimpleFactory.insert(User, username=username, password="", state=1, email="", img=img, ding='')

            username = user.username
            id = user.id

            token = myjwt.encode({'id': id})

            # 重定向操作
            self.redirect('http://localhost:8080/mystation/?id=%s&username=%s&token=%s' % (id, username, token))
            # return self.write(ret_json({'code':200,'username':user.username,'img':user.img}))


# code交换token  # 三方登录三步曲(2)
class Gitee_Back(BaseHandler):
    async def get(self):

        code = self.get_argument('code', None)

        token = SimpleFactory.get_token(code)

        # 最后一步,交换用户信息
        res = SimpleFactory.get_info(token, '', '', 'gitee')

        username = res[0]
        avatar_url = res[1]

        # 入库操作
        # 查询是否首次gitee登录
        user = await SimpleFactory.find_one(self.application.objects, User, username)

        # 序列化
        user = [myser(i) for i in user]
        myjwt = MyJwt()
        if user:
            # 存在  返回用户信息
            username = user[0]['username']
            id = user[0]['id']
            token = myjwt.encode({'id': id})
            print(token)
            self.redirect('http://localhost:8080/mystation/?id=%s&username=%s&token=%s' % (id, username, token))
        else:
            # 不存在 首次登录    入库
            user = await SimpleFactory.insert(User, username=username, password="", state=1, email="", img=avatar_url,
                                              ding='')

            username = user.username
            id = user.id
            token = myjwt.encode({'id': id})
            # 重定向操作
            self.redirect('http://localhost:8080/mystation/?id=%s&username=%s&token=%s' % (id, username, token))


# 钉钉回调地址
class DingDing_Back(BaseHandler):
    async def get(self):
        # 获取code
        code = self.get_argument('code')

        t = time.time()
        # 时间戳
        timestamp = str(int(round(t * 1000)))
        # appSecret = '8Mg-TTIu2JFgplrKVu1rLFn7EM7oEHw8Iun_Vsa9DGTGmgNgBUzm11A7DKuum8Em'

        # 请求接口，换取钉钉用户名
        # 定义载荷信息
        payload = {'tmp_auth_code': code}

        # 获取签名
        signature = SimpleFactory.get_signature(timestamp)

        # 获取用户信息
        rest = SimpleFactory.get_info(signature, timestamp, payload, 'dingding')

        username = rest['user_info']['nick']

        # 入库操作
        # 查询是否首次gitee登录
        user = await SimpleFactory.find_one(self.application.objects, User, rest['user_info']['nick'])

        # 序列化
        user = [myser(i) for i in user]
        print(user)
        if user:
            # 存在  返回用户信息
            username = user[0]['username']
            id = user[0]['id']
            self.redirect('http://localhost:8080/mystation/?id=%s&username=%s' % (id, username))
        else:
            # 不存在 首次登录    入库
            user = await SimpleFactory.insert(User, username=username, password="", state=1, email="", img='',
                                              ding=username)

            username = user.username
            id = user.id
            # 重定向操作
            self.redirect('http://localhost:8080/mystation/?id=%s&username=%s' % (id, username))

        # # 入库操作
        # # 查询是否首次gitee登录
        # user = await self.application.objects.execute(User.select().where(User.ding == rest['user_info']['nick']))
        # try:
        #     user = user[0]
        #     print(user)
        #     # return self.write(ret_json({'code':200,'meg':'登录成功','username':user.username,'id':user.id}))
        # except Exception as e:

        #     # user = await self.application.objects.create(User, username=rest['user_info']['nick'], password='', state=1,
        #     #                                              email=str(random.randint(1, 9999)),
        #     #                                              ding=rest['user_info']['nick'])

        #     user = SimpleFactory.insert(User, username=rest['user_info']['nick'], password='', state=1,
        #                                 email='', img='', ding=rest['user_info']['nick'])

        # 重定向操作
        # self.redirect('http://localhost:8080/mystation/?id=%s&username=%s' % (user.id, user.username))


# 定义图片文件流验证码
class MyCode(BaseHandler):

    async def get(self):
        # 接收前端传过来的电话号
        phone = self.get_argument('phone', None)

        # 定义画布的大小
        img_size = (120, 50)

        # 定义颜色种类对象      画布底色
        image = Image.new('RGB', img_size, 'green')

        # 定义画笔对象
        draw = ImageDraw.Draw(image, 'RGB')

        # 定义验证码内容
        source = '0123456789abcdefghjkmnpqrstuvwxyz'

        # 定义验证码的容器
        code_str = ''

        # 动态生成验证码
        for i in range(4):
            # 获取随机字符串
            tmp_num = random.randrange(len(source))

            # 获取一个随机字符串
            random_str = source[tmp_num]

            # 累加到容器中
            code_str += random_str

            # 将随机字符绘制
            draw.text((10 + 30 * i, 20), random_str, 'white')
        # 文件流对象
        buf = io.BytesIO()
        # 保存绘制好的图片
        image.save(buf, 'png')
        # 声明头部信息
        self.set_header('Content-Type', 'image/png')

        # redis存储动态码
        print(phone)
        redis = Redis()
        redis.delete(phone)
        redis.set(phone, code_str)

        # 返回图片
        return self.write(buf.getvalue())
        # return self.write(ret_json({'code':buf.getvalue(),'meg':code_str}))


# MySql
# 用户视图
class UserHandler(BaseHandler):

    def make_password(self, mypass):

        md5 = hashlib.md5()

        # 转码
        sign_utf8 = str(mypass + "123").encode(encoding="utf-8")
        md5.update(sign_utf8)

        return md5.hexdigest()

    # 账户密码登录
    async def get(self):

        # 接收参数  账密
        username = self.get_argument("username", None)

        password = self.get_argument("password", None)

        # # 非空验证
        # print(username,password)

        if username is None or username == '':
            ret = {'code': 403, 'meg': '用户名不能为空'}
            return self.write(ret_json(ret))

        if password is None or password == '':
            ret = {'code': 403, 'meg': '密码不能为空'}
            return self.write(ret_json(ret))

        # 异步查询      sql
        user = await self.application.objects.execute(
            User.select().where((User.username == username) & (User.password == self.make_password(password))))

        # 序列化操作
        try:
            user = user[0]

            # 加密操作
            myjwt = MyJwt()
            token = myjwt.encode({'id': user.id})
            return self.write(
                ret_json({'code': 200, 'meg': '登录成功', 'username': user.username, 'id': user.id, 'token': token}))

        except Exception as e:

            return self.write(ret_json({'code': 403, 'meg': '你的账户或者密码错误'}))

    # 注册
    async def post(self):

        # 接收参数  账密
        username = self.get_argument("username", None)

        password = self.get_argument("password", None)

        # # 非空验证
        # print(username,password)

        if username is None or username == '':
            ret = {'code': 403, 'meg': '用户名不能为空'}
            return self.write(ret_json(ret))

        if password is None or password == '':
            ret = {'code': 403, 'meg': '密码不能为空'}
            return self.write(ret_json(ret))

        # 合法性验证
        # 账户长度4-10位只能由数字字母下划线组成
        # 密码    6-18位 只能由字母开头,并且数字字母下划线组成

        # 虚位密码
        # 假设密码必须6位

        # password = password[-6:]

        # 正则格式
        result_username = re.compile(r'^\w{4,10}$')
        result_password = re.compile(r'^[a-zA-Z]\w{5,17}$')

        # 开始匹配
        if result_username.match(username) is None:
            ret = {'code': 403, 'meg': '您的用户名不合法'}
            return self.write(ret_json(ret))

        if result_password.match(password) is None:
            ret = {'code': 403, 'meg': '您的密码不合法'}
            return self.write(ret_json(ret))

        # 入库操作
        try:
            # user = User.create(username=username,password=self.make_password(password))
            user = await self.application.objects.create(User, username=username, password=self.make_password(password),
                                                         state=1, email=str(random.randint(1, 10000)))
        except Exception as e:
            ret = {"code": 403, "meg": "您的账户已经被占用"}
            return self.write(ret_json(ret))

        ret = {"code": 200, "msg": "注册成功"}
        return self.write(ret_json(ret))


# 回调接口
class EmailBack(UserHandler):

    async def get(self):
        id = self.get_argument('id', None)
        if id is None or id == '':
            return self.write(ret_json({'code': 403, 'meg': '用户id不能为空'}))

        # 解密操作
        myjwt = MyJwt()
        try:
            id = myjwt.decode(id)
        except Exception as e:
            return self.write(ret_json({'code': 403, 'meg': '请不要篡改用户信息/超过激活时间重新激活'}))
        id = id['data']['id']
        print(id)
        # 异步查询
        try:
            res = await self.application.objects.get(User, id=id)
        except Exception as e:
            return self.write({'code': 403, 'meg': '该用户不存在'})

        # 判断状态
        if res.state == 0:
            # 修改状态
            res.state = 1
            await self.application.objects.update(res)

            return self.write(ret_json({'code': 200, 'meg': '激活成功'}))
        else:
            return self.write(ret_json({'code': 200, 'meg': '您已经激活过,请不要重复激活'}))


# 邮箱激活接口
class EmailActive(UserHandler):

    # 重写post,入库逻辑
    async def post(self):
        # 接收参数   邮箱
        email = self.get_argument("email", None)
        code = self.get_argument("code", None)
        print(email, code, type(code))
        # 非空验证
        if email is None or email == '':
            ret = {'code': 403, 'meg': '邮箱输入不能为空'}
            return self.write(ret_json(ret))
        # 正则邮箱
        result_email = re.compile(r'^[1-9][0-9]{4,10}(@qq|@163)[.]com$')

        if result_email.match(email) is None:
            ret = {'code': 403, 'meg': '您的邮箱格式不合法'}
            return self.write(ret_json(ret))

        try:
            user = await self.application.objects.get(User, email=email)
        except Exception as e:
            return self.write({'code': 403, 'meg': '登录请先去注册邮箱'})

        # 查看表中是否有这个邮箱激活
        if user and user.state == 1:
            mymongo = MyMongo()
            res = mymongo.find_one({'email': email})
            if res:
                if int(res['code']) == int(code):
                    return self.write({'code': 200, 'meg': '登录成功'})
                else:
                    return self.write({'code': 403, 'meg': '验证码错误,请重新输入'})
            else:
                return self.write({'code': 403, 'meg': '验证码已失效,请重新获取'})

        # 重新激活操作
        if user and user.state == 0:
            # print(user)

            await send_mail(email, '邮箱测试', '信息', user.id)

            # 导入激活邮箱方法
            ret = {"code": 200, "meg": "请300秒内前往邮箱点击激活"}

            return self.write(ret_json(ret))

        # 入库操作
        try:
            res = await self.application.objects.create(User, email=email, state=0,
                                                        username=str(random.randint(1, 10000)))
        except Exception as e:
            return self.write(ret_json({'code': 403, 'meg': '你的邮箱已被注册'}))

        # loop = asyncio.get_event_loop()
        # loop.run_until_complete(send_mail(email,'邮箱测试','信息',res))

        await send_mail(email, '邮箱测试', '信息', res.id)

        # r = redis.Redis()
        # r.expire(email,30,1)
        # 导入激活邮箱方法
        ret = {"code": 200, "meg": "请300秒内前往邮箱点击激活"}

        return self.write(ret_json(ret))


# 邮箱验证码发送类
class EmailCode(EmailActive):

    def get_code(self):
        mystr = ''
        for i in range(4):
            mystr += str(random.randint(0, 9))
        return mystr

    # 重写post方法
    async def post(self):
        email = self.get_argument('email', None)

        print(email)

        try:
            user = await self.application.objects.get(User, email=email, state=1)
            # 将生成验证码入库
            if user:
                mycode = self.get_code()

                mymongo = MyMongo()

                mymongo.insert({'code': mycode, 'datetime': tzinfo.localize(datetime.datetime.now()), 'email': email})

                return self.write(ret_json({'code': 200, 'meg': mycode}))
        except Exception as e:

            # res = await self.application.objects.create(User, email=email, state=0,
            #                                             username=str(random.randint(1, 10000)))
            # await send_mail(email, '邮箱测试', '信息', res.id)

            # 导入激活邮箱方法
            ret = {"code": 200, "meg": "请先去注册邮箱"}

            return self.write(ret_json(ret))


# 用户详情接口
class UserInfo(BaseHandler):
    async def get(self):

        id = self.get_argument('id', None)

        # 查询
        try:
            user = await self.application.objects.get(User, id=id)
        except Exception as e:
            return self.write(ret_json({'查无此人'}))
        # 返回信息
        user = myser(user)
        print(user)
        return self.write(ret_json(user))


# 继承用户接口
class PhoneLogin(UserHandler):

    async def get(self):

        # 获取手机号
        phone = self.get_argument('phone', None)

        # 获取用户输入的验证码
        code = self.get_argument('code', None)

        # 通过phone获取mongo中的验证码
        mymongo = MyMongo()

        mongo_code = mymongo.find_one({'phone': phone})

        if mongo_code is None:
            return self.write(ret_json({'code': 403, 'meg': '验证码已失效'}))
        if int(code) == int(mongo_code['code']):
            # 是否曾经登录过
            user = await self.application.objects.execute(User.select().where(User.phone == phone))
            try:
                user = user[0]
                # return self.write(ret_json({'code':200,'meg':'登录成功'}))
                return self.write(ret_json(({'code': 200, 'meg': '登录成功', 'id': user.id, 'username': user.phone})))
            except Exception as e:
                # 入库操作
                user = await self.application.objects.create(User, username=phone, phone=phone, password='', state=1,
                                                             email=str(random.randint(1, 10000)))
                return self.write(
                    ret_json(({'code': 200, 'meg': '登录成功', 'id': user.id, 'username': user.phone, '1': 1})))
        else:
            return self.write(ret_json({'code': 403, 'meg': '你的验证码有误'}))


# 判断图片验证码
class ImgCode(UserHandler):

    async def get(self):
        phone = self.get_argument('phone', None)
        p_code = self.get_argument('p_code', None)
        email = self.get_argument('email', None)
        if phone:
            redis = Redis()
            ret = str(redis.get(phone), encoding='utf8')
            print(ret, p_code)
            if ret == p_code:
                return self.write(ret_json({'code': 200, 'meg': '图片校验成功'}))
            else:
                return self.write(ret_json({'code': 403, 'meg': '图片验证码错误'}))


# 短信验证码
class PhoneCode(UserHandler):

    async def get(self):
        phone = self.get_argument('phone', None)
        print(phone)
        result_phone = re.compile(r'^[1][3-9][0-9]{9}$')

        if phone is None or phone == None:
            return self.write(ret_json({'code': 403, 'meg': '请输入手机号'}))
        else:
            if result_phone.match(phone) is None:
                ret = {'code': 403, 'meg': '您的手机号不合法'}
                return self.write(ret_json(ret))
            else:
                # 实例化对象
                sendsms = SendSms()
                # 调用
                sendsms.send_sms(phone)
                mymongo = MyMongo()
                res = mymongo.find_one({'phone': phone})
                print(res['code'])
                return self.write(ret_json({'code': 200, 'meg': res['code']}))

# MongoDb
# 用户视图
# class UserHandler(BaseHandler):

#     def make_password(self, mypass):

#         md5 = hashlib.md5()

#         # 转码
#         sign_utf8 = str(mypass + "123").encode(encoding="utf-8")
#         md5.update(sign_utf8)

#         return md5.hexdigest()

#     # 账户密码登录
#     async def get(self):

#         # 接收参数  账密
#         username = self.get_argument("username", None)

#         password = self.get_argument("password", None)

#         # # 非空验证
#         # print(username,password)

#         if username is None or username == '':
#             ret = {'code': 403, 'meg': '用户名不能为空'}
#             return self.write(ret_json(ret))

#         if password is None or password == '':
#             ret = {'code': 403, 'meg': '密码不能为空'}
#             return self.write(ret_json(ret))

#         # 异步查询     

#         user=mymongo.find_one({'username':username,'password':self.make_password(password),'state':1})

#         # user = await self.application.objects.execute(
#         #     User.select().where((User.username == username) & (User.password == self.make_password(password))))

#         # 序列化操作
#         try:
#             user = user[0]

#             # 加密操作
#             myjwt = MyJwt()
#             token = myjwt.encode({'id': user.id})
#             return self.write(
#                 ret_json({'code': 200, 'meg': '登录成功', 'username': user.username, 'id': user.id, 'token': token}))

#         except Exception as e:

#             return self.write(ret_json({'code': 403, 'meg': '你的账户或者密码错误'}))

#     # 注册
#     async def post(self):

#         # 接收参数  账密
#         username = self.get_argument("username", None)

#         password = self.get_argument("password", None)

#         # # 非空验证
#         # print(username,password)

#         if username is None or username == '':
#             ret = {'code': 403, 'meg': '用户名不能为空'}
#             return self.write(ret_json(ret))

#         if password is None or password == '':
#             ret = {'code': 403, 'meg': '密码不能为空'}
#             return self.write(ret_json(ret))

#         # 合法性验证
#         # 账户长度4-10位只能由数字字母下划线组成
#         # 密码    6-18位 只能由字母开头,并且数字字母下划线组成

#         # 虚位密码
#         # 假设密码必须6位

#         # password = password[-6:]

#         # 正则格式
#         result_username = re.compile(r'^\w{4,10}$')
#         result_password = re.compile(r'^[a-zA-Z]\w{5,17}$')

#         # 开始匹配
#         if result_username.match(username) is None:
#             ret = {'code': 403, 'meg': '您的用户名不合法'}
#             return self.write(ret_json(ret))

#         if result_password.match(password) is None:
#             ret = {'code': 403, 'meg': '您的密码不合法'}
#             return self.write(ret_json(ret))

#         # 入库操作
#         try:
#             mymongo.insert({"username":username,'password':self.make_password(password),'state':1,'email':str(random.randint(1, 10000))})
#             # user = User.create(username=username,password=self.make_password(password))
#             # user = await self.application.objects.create(User, username=username, password=self.make_password(password),
#             #                                              state=1, email=str(random.randint(1, 10000)))
#         except Exception as e:
#             ret = {"code": 403, "meg": "您的账户已经被占用"}
#             return self.write(ret_json(ret))

#         ret = {"code": 200, "msg": "注册成功"}
#         return self.write(ret_json(ret))


# # 回调接口
# class EmailBack(UserHandler):

#     async def get(self):
#         mymongo = MyMongo()
#         id = self.get_argument('id', None)
#         if id is None or id == '':
#             return self.write(ret_json({'code': 403, 'meg': '用户id不能为空'}))

#         # 解密操作
#         myjwt = MyJwt()
#         try:
#             id = myjwt.decode(id)
#         except Exception as e:
#             return self.write(ret_json({'code': 403, 'meg': '请不要篡改用户信息/超过激活时间重新激活'}))
#         id = id['data']['id']
#         print(id)
#         # 异步查询
#         try:
#             # res = await self.application.objects.get(User, id=id)
#             res = mymongo.find_one({'_id': ObjectId(id), 'state': 0})
#         except Exception as e:
#             return self.write({'code': 403, 'meg': '该用户不存在'})

#         # 判断状态
#         if res.state == 0:
#             # 修改状态
#             res.state = 1

#             mymongo.update({'_id':res['_id']},{'$set':{'state':1}})
#             # await self.application.objects.update(res)

#             return self.write(ret_json({'code': 200, 'meg': '激活成功'}))
#         else:
#             return self.write(ret_json({'code': 200, 'meg': '您已经激活过,请不要重复激活'}))


# # 邮箱激活接口
# class EmailActive(UserHandler):

#     # 重写post,入库逻辑
#     async def post(self):
#         # 接收参数   邮箱
#         email = self.get_argument("email", None)
#         code = self.get_argument("code", None)
#         print(email, code, type(code))
#         # 非空验证
#         if email is None or email == '':
#             ret = {'code': 403, 'meg': '邮箱输入不能为空'}
#             return self.write(ret_json(ret))
#         # 正则邮箱
#         result_email = re.compile(r'^[1-9][0-9]{4,10}(@qq|@163)[.]com$')

#         if result_email.match(email) is None:
#             ret = {'code': 403, 'meg': '您的邮箱格式不合法'}
#             return self.write(ret_json(ret))

#         try:
#             mymongo = MyMongo()
#             user = mymongo.find_one({'username':str(random.randint(1111, 9999)),'email':email,'state':0})
#             # user = await self.application.objects.get(User, email=email)
#         except Exception as e:
#             return self.write({'code': 403, 'meg': '登录请先去注册邮箱'})

#         # 查看表中是否有这个邮箱激活
#         if user and user.state == 1:
#             mymongo = MyMongo()
#             res = mymongo.find_one({'email': email})
#             if res:
#                 if int(res['code']) == int(code):
#                     return self.write({'code': 200, 'meg': '登录成功'})
#                 else:
#                     return self.write({'code': 403, 'meg': '验证码错误,请重新输入'})
#             else:
#                 return self.write({'code': 403, 'meg': '验证码已失效,请重新获取'})

#         # 重新激活操作
#         if user and user.state == 0:
#             # print(user)

#             await send_mail(email, '邮箱测试', '信息', user.id)

#             # 导入激活邮箱方法
#             ret = {"code": 200, "meg": "请300秒内前往邮箱点击激活"}

#             return self.write(ret_json(ret))

#         # 入库操作
#         try:
#             mymongo = MyMongo()
#             res = mymongo.insert({'username':str(random.randint(1111, 9999)),'email':email,'state':0})
#             # res = await self.application.objects.create(User, email=email, state=0,
#             #                                             username=str(random.randint(1, 10000)))
#         except Exception as e:
#             return self.write(ret_json({'code': 403, 'meg': '你的邮箱已被注册'}))

#         # loop = asyncio.get_event_loop()
#         # loop.run_until_complete(send_mail(email,'邮箱测试','信息',res))
#         print(res)

#         await send_mail(email, '邮箱测试', '信息', res.id)

#         # r = redis.Redis()
#         # r.expire(email,30,1)
#         # 导入激活邮箱方法
#         ret = {"code": 200, "meg": "请300秒内前往邮箱点击激活"}

#         return self.write(ret_json(ret))


# # 邮箱验证码发送类
# class EmailCode(EmailActive):

#     def get_code(self):
#         mystr = ''
#         for i in range(4):
#             mystr += str(random.randint(0, 9))
#         return mystr

#     # 重写post方法
#     async def post(self):
#         email = self.get_argument('email', None)

#         print(email)

#         try:
#             mymongo = MyMongo()
#             user = mymongo.find_one(email=email,state=1)
#             # print(user)
#             # user = await self.application.objects.get(User, email=email, state=1)
#             # 将生成验证码入库
#             if user:
#                 mycode = self.get_code()

#                 mymongo = MyMongo()

#                 mymongo.insert({'code': mycode, 'datetime': tzinfo.localize(datetime.datetime.now()), 'email': email})

#                 return self.write(ret_json({'code': 200, 'meg': mycode}))
#         except Exception as e:

#             # res = await self.application.objects.create(User, email=email, state=0,
#             #                                             username=str(random.randint(1, 10000)))
#             # await send_mail(email, '邮箱测试', '信息', res.id)

#             # 导入激活邮箱方法
#             ret = {"code": 200, "meg": "请先去注册邮箱"}

#             return self.write(ret_json(ret))
